package com.Suyin.pma.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username,password,enabled"+"FROM users WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username authority"+"FROM authorities WHERE username = ?")
                .passwordEncoder(bCryptPasswordEncoder);


                /*.withDefaultSchema()
                .withUser("Suyin")
                .password("123456")
                .roles("USER")
                .and()
                .withUser("suyin")
                .password("123")
                .roles("USER")
                .and()
                .withUser("suy")
                .password("1234")
                .roles("Admin");
                 */
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
             //   .antMatchers("/projects/save").hasRole("Admin")
             //   .antMatchers("/students/new").hasRole("Admin")
             //   .antMatchers("/projects/new").hasRole("Admin")
              //  .antMatchers("/students/save").hasRole("Admin")
                .antMatchers("/","/**").permitAll()
                .and()
                .formLogin();


    }
}
